#!/usr/bin/env python3
# -*- coding: utf-8 -*

"""
使用ifaddr库获取IPv6地址的工具模块
提供简单的函数来获取本机的IPv6地址
"""

import ifaddr
from typing import List, Dict, Optional

def get_ipv6_addresses() -> List[Dict[str, str]]:
    """
    获取所有IPv6地址
    
    Returns:
        List[Dict]: 包含接口、地址、前缀长度和类型的字典列表
    """
    ipv6_addresses = []
    
    try:
        adapters = ifaddr.get_adapters()
        
        for adapter in adapters:
            if adapter.ips:
                for ip in adapter.ips:
                    if ip.is_IPv6:
                        # 从元组中提取IP地址
                        ip_tuple = ip.ip
                        if isinstance(ip_tuple, tuple) and len(ip_tuple) > 0:
                            ip_str = ip_tuple[0]  # 取元组的第一个元素
                        else:
                            ip_str = str(ip_tuple)
                        
                        # 判断地址类型
                        addr_type = get_ipv6_type(ip_str)
                        
                        ipv6_addresses.append({
                            'interface': adapter.name,
                            'address': ip_str,
                            'netmask': ip.network_prefix,
                            'type': addr_type,
                            'is_global': is_global_ipv6(ip_str),
                            'is_link_local': is_link_local_ipv6(ip_str)
                        })
    except Exception:
        pass
    
    return ipv6_addresses

def get_ipv6_type(ipv6_addr: str) -> str:
    """判断IPv6地址类型"""
    if ipv6_addr == '::1':
        return 'loopback'
    elif ipv6_addr.startswith('fe80:'):
        return 'link-local'
    elif ipv6_addr.startswith('fc00:') or ipv6_addr.startswith('fd00:'):
        return 'unique-local'
    elif ipv6_addr.startswith('2001:db8:'):
        return 'documentation'
    elif ipv6_addr.startswith('ff00:'):
        return 'multicast'
    elif ipv6_addr.startswith('2001:'):
        return 'global-unicast'
    elif ipv6_addr.startswith('2002:'):
        return '6to4'
    else:
        return 'other'

def is_global_ipv6(ipv6_addr: str) -> bool:
    """判断是否为全局IPv6地址"""
    # 排除本地地址
    if (ipv6_addr == '::1' or 
        ipv6_addr.startswith('fe80:') or 
        ipv6_addr.startswith('fc00:') or 
        ipv6_addr.startswith('fd00:')):
        return False
    return True

def is_link_local_ipv6(ipv6_addr: str) -> bool:
    """判断是否为链路本地IPv6地址"""
    return ipv6_addr.startswith('fe80:')

def get_global_ipv6() -> Optional[str]:
    """获取全局IPv6地址"""
    addresses = get_ipv6_addresses()
    
    for addr in addresses:
        if addr['is_global']:
            return addr['address']
    
    return None

def get_link_local_ipv6(interface: str = 'eth0') -> Optional[str]:
    """获取指定接口的链路本地IPv6地址"""
    addresses = get_ipv6_addresses()
    
    for addr in addresses:
        if addr['interface'] == interface and addr['is_link_local']:
            return addr['address']
    
    return None

def get_main_ipv6() -> Optional[str]:
    """获取主要IPv6地址（优先全局，其次链路本地）"""
    # 首先尝试获取全局IPv6地址
    global_ipv6 = get_global_ipv6()
    if global_ipv6:
        return global_ipv6
    
    # 如果没有全局地址，获取eth0的链路本地地址
    return get_link_local_ipv6('eth0')

def get_ipv6_by_interface(interface: str) -> Optional[str]:
    """获取指定接口的IPv6地址（优先全局地址）"""
    addresses = get_ipv6_addresses()
    
    # 优先查找全局地址
    for addr in addresses:
        if addr['interface'] == interface and addr['is_global']:
            return addr['address']
    
    # 如果没有全局地址，查找链路本地地址
    for addr in addresses:
        if addr['interface'] == interface and addr['is_link_local']:
            return addr['address']
    
    return None

def has_global_ipv6() -> bool:
    """检查是否有全局IPv6地址"""
    return get_global_ipv6() is not None

def has_ipv6() -> bool:
    """检查是否有任何IPv6地址"""
    return len(get_ipv6_addresses()) > 0

# 便捷函数
def get_current_ipv6() -> Optional[str]:
    """
    获取当前可用的IPv6地址
    这是最常用的函数，返回最适合使用的IPv6地址
    
    Returns:
        Optional[str]: 当前IPv6地址，如果没有则返回None
    """
    return get_main_ipv6()

# 示例用法
if __name__ == '__main__':
    print("ifaddr IPv6地址获取工具测试")
    print("=" * 30)
    
    # 获取当前IPv6地址
    current_ipv6 = get_current_ipv6()
    if current_ipv6:
        print(f"当前IPv6地址: {current_ipv6}")
    else:
        print("未找到IPv6地址")
    
    # 检查是否有全局IPv6
    if has_global_ipv6():
        print("✅ 有全局IPv6地址")
        print(f"全局IPv6: {get_global_ipv6()}")
    else:
        print("❌ 无全局IPv6地址")
    
    # 显示所有IPv6地址
    all_addresses = get_ipv6_addresses()
    if all_addresses:
        print(f"\n所有IPv6地址 ({len(all_addresses)}个):")
        for addr in all_addresses:
            print(f"  {addr['interface']}: {addr['address']} ({addr['type']})")
    else:
        print("未找到任何IPv6地址")
